<?php

namespace app\models;

use yii\db\ActiveRecord;

class Incr extends ActiveRecord
{

    /** 预热视频播放次数 */
    const INCR_PUBLICITY_VIDEO_PLAY_STAT = [
        'publicity_video_play_stat',
        '预热视频播放次数'
    ];

    /** H5浏览次数 */
    const INCR_PUBLICITY_BROWSE_STAT = [
        'publicity_browse_stat',
        'H5浏览次数'
    ];

    /** 底部按钮1点击次数 */
    const INCR_JUMP_LINK1_STAT = [
        'jump_link1_stat',
        '底部按钮1点击次数'
    ];

    /** 底部按钮2点击次数 */
    const INCR_JUMP_LINK2_STAT = [
        'jump_link2_stat',
        '底部按钮2点击次数'
    ];

    /** 会员登录抽奖次数 */
    const INCR_MEMBER_APPLY_STAT = [
        'member_apply_stat',
        '会员登录抽奖次数'
    ];

    /**
     * 通过key获取一条记录
     * @return array
     */
    public static function getAllKey()
    {
        $rows = self::find()
            ->asArray()
            ->all();

        $rows = array_column($rows, null, 'key');

        return $rows;
    }

    /**
     * 预热视频播放次数
     * @return string
     */
    public static function publicityVideoPlayStat()
    {
        return self::incr(self::INCR_PUBLICITY_VIDEO_PLAY_STAT[0]);
    }

    /**
     * 预热页面浏览次数
     * @return string
     */
    public static function publicityBrowseStat()
    {
        return self::incr(self::INCR_PUBLICITY_BROWSE_STAT[0]);
    }

    /**
     * 底部按钮1点击次数
     * @return string
     */
    public static function jumpLink1Stat()
    {
        return self::incr(self::INCR_JUMP_LINK1_STAT[0]);
    }

    /**
     * 底部按钮2点击次数
     * @return string
     */
    public static function jumpLink2Stat()
    {
        return self::incr(self::INCR_JUMP_LINK2_STAT[0]);
    }

    /**
     * 会员登录抽奖次数
     * @return string
     */
    public static function memberApplyStat()
    {
        return self::incr(self::INCR_MEMBER_APPLY_STAT[0]);
    }

    /**
     * 自增序列
     * @param $key
     * @return string
     */
    private static function incr($key)
    {
        $sql = 'INSERT INTO ' . self::tableName() . ' (`key`) VALUES (:key) ON DUPLICATE KEY UPDATE incr = LAST_INSERT_ID(incr + 1)';
        $params = array(
            ':key' => $key
        );

        $connection = self::getDb();
        $transactio = $connection->beginTransaction();

        $connection->createCommand($sql, $params)
            ->execute();

        $incr = $connection->getLastInsertID();

        $transactio->commit();

        return $incr;
    }

}